package org.example.gift.service.impl;

@Service
public class CommonServiceImpl implements ICommonService {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;

    @Override
    public String createImgCode(String uuid) {
        //1.生成图形验证码里面的数字
        String code = StrUtils.getRandomString(4);
        //2.把数字和uuid组合放到redis里面  5分钟自动过期
        redisTemplate.opsForValue().set(uuid,code,5, TimeUnit.MINUTES);
        //3.要把数字转换成一张图片
        try {
            return VerifyCodeUtils.verifyCode(102, 42, code);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //4.返回一张图片
        return null;
    }

    @Override
    public void sendPhoneCode(PhoneCodeDto phoneCodeDto) {
        //组装redis存储在redis的key
        String key = phoneCodeDto.getType()+":"+phoneCodeDto.getPhone();
        String code = StrUtils.getRandomString(6);

        if (phoneCodeDto.getType().equals("REG")) {


            Object o = redisTemplate.opsForValue().get(phoneCodeDto.getUuid());
            RonghuaAssert.isNotNull(o, SystemErrorCode.RESPONSE_CODE_500002);

            RonghuaAssert.isEq(phoneCodeDto.getImgCode(),o.toString(),SystemErrorCode.RESPONSE_CODE_500002);
        }


        Object codeInRedis = redisTemplate.opsForValue().get(key);
        if (codeInRedis!=null){
            Long preTime = Long.valueOf(codeInRedis.toString().split(":")[1]);
            if ((System.currentTimeMillis()-preTime)<60*1000){
                throw new BusinessException(SystemErrorCode.RESPONSE_CODE_500003);
            }
            code=codeInRedis.toString().split(":")[0];
        }

        redisTemplate.opsForValue().set(key,code+":"+System.currentTimeMillis(),5,TimeUnit.MINUTES);
        //把验证码发送到用户的手机上
        boolean b = SmsUtils.sendMsg(phoneCodeDto.getPhone(), code);
        System.out.println("本次的验证码为:"+code);

    }
}